<?php

namespace App\Core\Database;

use Illuminate\Support\Facades\Cache;
use Redis;

class SqlCacher extends Cacher
{

    protected $prefix = 'model_query_cache:';

    /**
     * @var App\Core\Database\QueryBuilder
     */
    protected $builder;

    public function __construct($builder)
    {
        $this->builder = $builder;
    }

    public function cacheQuery(\Closure $queryClosure)
    {
        $expire = $this->getExpire();

        if($expire == 0) {
            return Redis::set($this->getCacheKey(), $queryClosure());            
        }

        return Redis::set($this->getCacheKey(), $queryClosure(), $this->getExpire());
    }

    public function getCacheKey()
    {
        $identifier = $this->builder->toSql() .
            serialize($this->builder->getBindings());

        return $this->prefix(md5($identifier));
    }

    protected function prefix($key)
    {
        return $this->prefix . $this->getTable() . ':'  . $key;
    }


    public function flush()
    {
        $keys = Cache::get($this->redis->prefix('*'));

        foreach ($keys as $key) {
            Cache::del($key);
        }
    }

    public function getTable()
    {
        return $this->builder->getConnection()->getTablePrefix() . $this->builder->from;
    }

}
